// stores/cart.ts
import { defineStore } from 'pinia';

declare interface IAddress {
	provinceName: string, 
	cityName: string, 
	countyName: string, 
	detailInfo: string
}
declare interface IUserInfo {
	name: string, 
	[index: string]: string
}
declare interface IUser {
	address: IAddress, 
	userinfo: IUserInfo,
	token: string, 
	redirectInfo: any, 
}

const useUserStore_ = defineStore('user', {
	state: (): IUser => {
		return { 
			address: JSON.parse(uni.getStorageSync('address') || '{}'),
			token: uni.getStorageSync('token') || '',
			// 用户的信息对象
			userinfo: JSON.parse(uni.getStorageSync('userinfo') || '{}'),
			// 重定向的 Object 对象
			redirectInfo: null
		};
	},
	// 也可以这样定义
	// state: () => ({ count: 0 })
	actions: {
		// 更新收货地址
		updateAddress(address: IAddress) {
			this.address = address
			this.saveAddressToStorage()
		},
		// 持久化存储 address
		saveAddressToStorage() {
			uni.setStorageSync('address', JSON.stringify(this.address))
		},
		updateUserInfo(userinfo: IUserInfo) {
			this.userinfo = userinfo
			this.saveUserInfoToStorage()
		},
		saveUserInfoToStorage() {
			uni.setStorageSync('userinfo', JSON.stringify(this.userinfo))
		},
		updateToken(token: string) {
			this.token = token
			this.saveTokenToStorage()
		},
		saveTokenToStorage() {
			uni.setStorageSync('token', this.token)
		},
		updateRedirectInfo(info: any) {
			this.redirectInfo = info
			console.log(this.redirectInfo)
		}
	},
  getters: {
		// 收货地址
		addstr(): string {
			if (!this.address.provinceName) return ''

			return this.address.provinceName + this.address.cityName + this.address.countyName + this.address.detailInfo
		}
	}
});

export const useUserStore = useUserStore_()
